package org.com.gamemall.Controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.com.gamemall.Entity.User;
import org.com.gamemall.Service.IUserService;
import org.com.gamemall.Utity.RedisCacheTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 277
 * @since 2025-07-23
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisCacheTime redisCacheTime;
    private static final String LOGIN_KEY = "login:user:";

    @PostMapping("/login")
    public User login(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, map.get("username"));
        User user = userService.getOne(wrapper);
        if (user == null) {
            User user2 = new User();
            user2.setUsername(map.get("username").toString());
            user2.setPassword(map.get("password").toString());
            userService.save(user2);
            user = user2; // 将新用户赋值给 user
        }
        request.getSession().setAttribute("user", user.getId());
        stringRedisTemplate.opsForValue().set("login:user:", String.valueOf(user.getId()), 2, TimeUnit.MINUTES);
        redisCacheTime.Refreshtime(LOGIN_KEY, 20);
        return user;
    }

}
